<?php
/**
 * PddCopyLogDao.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:52
 */

namespace common\jobs\dao;


use common\exception\ValidatorException;
use common\jobs\models\PddCopyLogs;
use common\library\BaseDao;
use Yii;
class PddCopyLogDao extends BaseDao
{

    /**
     * 写入复制批次表
     * @param array $data
     * @return PddCopyLogs
     * @throws ValidatorException
     */
    public function insertData(array $data)
    {
        $copyLog = new PddCopyLogs();

        $copyLog->load($data,'');

        if (!$copyLog->validate()) {
            throw new ValidatorException($copyLog->errorsToString());
        }

        if($copyLog->save())
        {
            return $copyLog;
        }else{
            throw new ValidatorException($copyLog->errorsToOneString());
        }
    }

    /**
     * 通过主键获取信息
     * @param int $pk
     * @return PddCopyLogs|null
     */
    public function getBatchInfoByPk(int $pk)
    {
        return PddCopyLogs::findOne(['id'=>$pk]);
    }


    /**
     * 获取指定用户指定店铺的最后一条批次信息
     * @param int $uid
     * @param int $mall_id
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getLastOne(int $uid,int $mall_id)
    {
        return PddCopyLogs::find()->where([
            'uid' => $uid,
            'mall_id' => $mall_id
        ])->orderBy('id DESC')->limit(1)->one();
    }


    /**
     * 获取批次号名称
     * @param int $uid
     * @param int $mall_id
     * @return string
     */
    public function getBatchName(int $uid,int $mall_id)
    {
        $cacheKey = date('Ymd').':'.$uid.':'.$mall_id;


        $cacheNum = Yii::$app->redis->get($cacheKey);

        if(!$cacheNum)
        {
            Yii::$app->redis->setex($cacheKey,86400,1);

            return date('Ymd').'-'.sprintf("%04d", 1);
        }else{
            Yii::$app->redis->incr($cacheKey);
            return date('Ymd').'-'.sprintf("%04d", $cacheNum+1);
        }

    }

}